const config = require('../config/default')
const jsonwebtoken = require('jsonwebtoken')
const util = require('util');

module.exports = async (ctx, next) => {
  // 中间件统一验证token
  let valid = await util.promisify(jsonwebtoken.verify)(ctx.cookies.get(process.env['token.name']), config.SECRET).catch(err => {
      if (err.name == 'TokenExpiredError') {
        ctx.body = {
          status: 403,
          message: '登录失效'
        }
        ctx.response.status = 403
      } else if (err.name === 'JsonWebTokenError') {
        ctx.body = {
          status: 403,
          message: '无效token'
        }
        ctx.response.status = 403
      }
      return false
  })
  if (valid) {
    ctx._token = valid
    await next()
  }
}